# -*- coding: utf-8 -*-
# @Author  : Lison Song
# @Time    : 2023/3/16 15:44
import json
import logging
from datetime import datetime, timedelta
from flask import Blueprint, render_template, request, session, jsonify, current_app
from flask_login import login_required, current_user
from sqlalchemy import desc
from applications.common.utils.validate import str_escape
from applications.common.utils.http import table_api, fail_api, success_api
from applications.extensions import db
from applications.models import Weixin_articles, Weixin_Official_Acc, Weixin_Official_Acc_log
from applications.common.utils.mytools import MyTools
from applications.models.admin_robot_info import Robot_Info
from applications.common.appenv import HttpBaseCode

weixin_article_bp = Blueprint('weixinArticle', __name__, url_prefix='/api/weixinArticle')


#  添加订阅号文章
@weixin_article_bp.post('/add')
def add():
    req_json = request.json
    # print(req_json)
    current_app.logger.info(json.dumps(req_json, indent=4, ensure_ascii=False))
    wx_name = str_escape(req_json.get('name'))
    robot_name = str_escape(req_json.get('robot_name'))
    create_at = str_escape(req_json.get('captime'))
    articles = req_json.get('articles')
    elapsed_time = req_json.get('elapsed_time')

    if not wx_name:
        return fail_api(msg="订阅号名称不能为空")

    wx_offac = Weixin_Official_Acc.query.filter_by(wx_name=wx_name).first()
    wx_offac_id = wx_offac.id
    # print(f"公众号ID是: {wx_offac_id}")
    robot = Robot_Info.query.filter_by(code=robot_name).first()
    robot_id = 1
    if robot:
        robot_id = robot.id
    if not wx_offac_id:
        return fail_api(msg="公众号不存在")

    # 判断文章列表为空 记录流水 结束入库流程
    if not articles:
        object_date, object_time, day, time = MyTools.dateformartforvar(create_at)
        log_stream = Weixin_Official_Acc_log(wx_id=wx_offac_id, robot_id=robot_id, article_nu=0,
                                             indb_nu=0, update_at=create_at, elapsed_time=elapsed_time,
                                             year=object_date.year, month=object_date.month, day=day, time=time)
        db.session.add(log_stream)
        db.session.commit()
        current_app.logger.info(
            f"{robot_name} 公众号采集流水入库成功：wx_id={wx_offac_id}, robot_id={robot_id}, article_nu=0,indb_nu=0, update_at={create_at}, elapsed_time={elapsed_time},year={object_date.year}, month={object_date.month}, day={day}, time={time}")

        return fail_api(msg="订阅号文章信息不能为空")

    article_nu = len(articles)
    indb_nu = 0
    for article_info in articles:
        # print(article_info)
        article_key = ""
        title = article_info['title']
        url = MyTools.pre_wx_article_url(article_info['url'])
        articletime = article_info['articletime']
        ## 如果文章 URL 为空则跳过
        if url == "":
            continue

        try:
            '''
            微信订阅号文章：https://mp.weixin.qq.com/s/wSDnGUcA0Z6MtbRlaRQbCa
            使用url 产生 uuid 作为标识 文章唯一性的 key
            '''
            article_key = MyTools.getUUID(url)
        except Exception as e:
            # print(e)
            current_app.logger.error(e)

        # print(f"{title}  {url} {article_key}")
        if bool(Weixin_articles.query.filter_by(article_key=article_key).count()) or bool(
                Weixin_articles.query.filter_by(article_title=title, article_time=articletime).count()):
            # print(f"{robot_name} 文章已经存在：{wx_name} {title} ")
            current_app.logger.info(f"{robot_name} 文章已经存在：{wx_name} {title} ")
        else:
            try:
                article = Weixin_articles(wx_name=wx_name, article_title=title, article_url=url,
                                          article_key=article_key, create_at=create_at, wx_offac_id=wx_offac_id,
                                          robot_id=robot_id, article_time=articletime)
                indb_nu = indb_nu + 1
                db.session.add(article)
                db.session.commit()
                current_app.logger.info(f"{robot_name} 保存成功：{wx_name} {title} {url}")
            except Exception as e:
                current_app.logger.error(e)

    try:
        # 更新公众号表 t_weixin_official_acc 文章采集情况
        # 更新机器人最新的运行时间
        oa_article_nu = Weixin_articles.query.filter_by(wx_name=wx_name).count()
        Weixin_Official_Acc.query.filter_by(wx_name=wx_name).update(
            {'article_nu': oa_article_nu, 'update_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
        # 更新机器人最新运行日期
        Robot_Info.query.filter_by(id=robot_id).update(
            {'update_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
        db.session.commit()

        # 更新 t_weixin_official_acc_log 表的日志流水
        object_date, object_time, day, time = MyTools.dateformartforvar(create_at)
        log_stream = Weixin_Official_Acc_log(wx_id=wx_offac_id, robot_id=robot_id, article_nu=article_nu,
                                             indb_nu=indb_nu, update_at=create_at, elapsed_time=elapsed_time,
                                             year=object_date.year, month=object_date.month, day=day, time=time)
        db.session.add(log_stream)
        db.session.commit()
        current_app.logger.info(
            f"{robot_name} 公众号采集流水入库成功：wx_id={wx_offac_id}, robot_id={robot_id}, article_nu={article_nu},indb_nu={indb_nu}, update_at={create_at}, elapsed_time={elapsed_time},year={object_date.year}, month={object_date.month}, day={day}, time={time}")

    except Exception as e:
        print(e)
    return success_api(msg="数据收到了")


#  获取订阅号文章
@weixin_article_bp.post('/get')
def get():
    req_json = request.json
    wx_names = req_json.get('wx_names')
    startdate = req_json.get('startdate')
    enddate = req_json.get('enddate')
    # print(wx_names)
    # print(isinstance(wx_names, list))
    # print(len(wx_names))
    if not isinstance(wx_names, list) or len(wx_names) <= 0:
        return fail_api(msg="订阅号名称信息不能为空")
    else:
        filters = []
        filters.append(Weixin_articles.wx_name.in_(wx_names))
        if startdate:
            startdate = datetime.strptime(startdate, '%Y-%m-%d')
            filters.append(Weixin_articles.create_at >= startdate)
        if enddate:
            enddate = datetime.strptime(enddate, '%Y-%m-%d') + timedelta(days=1)
            filters.append(Weixin_articles.create_at <= enddate)
        query = db.session.query(
            Weixin_articles
        ).filter(*filters).order_by(Weixin_articles.wx_name).all()
        print(query)
        result = {}
        result['code'] = 0
        result['data'] = []
        for item in query:
            article = {}
            article['wx_name'] = item.wx_name
            article['article_title'] = item.article_title
            article['article_url'] = item.article_url
            article['create_at'] = item.create_at
            result['data'].append(article)
        result['count'] = len(query)
        return jsonify(result)


#  机器人获取任务订阅号
@weixin_article_bp.get('/getOffAccByHostname')
def getOffAccByHostname():
    robotname = str_escape(request.args.get('robotname', type=str))
    # print(hostname)
    robot = Robot_Info.query.filter_by(code=robotname).first()
    filters = []
    filters.append(Weixin_Official_Acc.robot_id == robot.id)
    filters.append(Weixin_Official_Acc.enable == 1)
    query = db.session.query(Weixin_Official_Acc).filter(*filters).all()
    aclist = []
    for item in query:
        aclist.append(item.wx_name)
    # print(aclist)
    result = {'offaccs': aclist, 'count': len(aclist), 'robot': robotname}
    current_app.logger.info(json.dumps(result, indent=4, ensure_ascii=False))
    return jsonify(result)
